package com.hqq.concurrency.reactor.framework;

import java.nio.channels.SelectionKey;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * ThreadPoolDispatcher
 * 使用工作线程池转发事件操作 由于IO操作不在当前线程执行 因此具有更好的性能
 * Created by heqianqian on 2017/8/5.
 */
public class ThreadPoolDispatcher implements Dispatcher {

    private ExecutorService executorService;

    public ThreadPoolDispatcher(int count) {
        //分配指定数量的线程
        executorService = Executors.newFixedThreadPool(count);
    }

    @Override
    public void onChannelReadEvent(AbstractNIOChannel channel, Object data, SelectionKey selectionKey) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                channel.getHandler().handleChannelRead(channel,data,selectionKey);
            }
        });
    }

    @Override
    public void stop() throws InterruptedException {
        executorService.shutdown();
        executorService.awaitTermination(5, TimeUnit.SECONDS);
    }
}
